<?php

namespace app\controller;

use think\Request;
use think\Response;

class Health
{
    /**
     * 健康检查
     */
    public function index(Request $request): Response
    {
        $data = [
            'status' => 'ok',
            'message' => '系统运行正常',
            'timestamp' => date('Y-m-d H:i:s'),
            'version' => '1.0.0',
            'database' => $this->checkDatabase(),
            'cache' => $this->checkCache()
        ];

        return json($data);
    }

    /**
     * 检查数据库连接
     */
    private function checkDatabase(): array
    {
        try {
            $db = \think\facade\Db::connect();
            $result = $db->query('SELECT 1');

            return [
                'status' => 'connected',
                'message' => '数据库连接正常'
            ];
        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => '数据库连接失败: ' . $e->getMessage()
            ];
        }
    }

    /**
     * 检查缓存连接
     */
    private function checkCache(): array
    {
        try {
            $cache = \think\facade\Cache::store();
            $cache->set('health_check', time(), 60);
            $value = $cache->get('health_check');

            if ($value) {
                return [
                    'status' => 'connected',
                    'message' => '缓存连接正常'
                ];
            } else {
                return [
                    'status' => 'error',
                    'message' => '缓存读写失败'
                ];
            }
        } catch (\Exception $e) {
            return [
                'status' => 'error',
                'message' => '缓存连接失败: ' . $e->getMessage()
            ];
        }
    }
}